import React, { Component } from 'react'
import { connect } from 'dva';
import Link from 'umi/link';
import { Form, Cascader } from 'antd';
import { SearchRow, SearchCol, SearchButton } from '@/styled/form';
import { DICT, LOCATION } from '../enum';
import { DropDownSelectObj } from '@/components/DropDownSelect';

import { UmiComponentProps, SearchComponentProps } from '@/common/type';

interface P {
  dict?: any;
  cond?: {
    ownerId: string;
    pageNum: number;
    pageSize: number;
  };
  loading?: true;
  location?: Array<any>;
}

const FormItem = Form.Item;

type Props = P & UmiComponentProps & SearchComponentProps;

@connect(({ device_outdoor_hydrant, loading }) => ({
  dict: device_outdoor_hydrant.dict || {},
  cond: device_outdoor_hydrant.cond || {},
  location: device_outdoor_hydrant.location || [],
  loading: loading.effects['device_outdoor_hydrant/queryLocation']
}))
class Search extends Component<Props, any> {

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'device_outdoor_hydrant/init',
      payload: {
        dict: { keyList: DICT }
      }
    }).then(() => {
      const { cond, form } = this.props;
      const { pageNum, pageSize, ...searchParams } = cond;
      form.setFieldsValue(searchParams);
    });
  }

  private search = (e) => {
    e.preventDefault();
    const { dispatch } = this.props;
    this.props.form.validateFields((err: undefined | {}, values: any) => {
      if (!err) {
        const ans = Array.isArray(values.buildList) && values.buildList[values.buildList.length - 1] ? values.buildList[values.buildList.length - 1].split('%%')[0] : null;
        dispatch({
          type: 'device_outdoor_hydrant/updateCond',
          payload: {
            ...values,
            floorId: null,
            areaId: null,
            buildId: null,
            ...(Array.isArray(values.buildList) && LOCATION[values.buildList.length - 1] ? { [`${LOCATION[values.buildList.length - 1].type}Id`]: ans } : {}),
          }
        });
        this.props.initCurrent()
      }
    });
  };

  private handleSelect = (v, option) => {
    const { cond = {}, dispatch } = this.props;

    const ans = v[v.length - 1] ? v[v.length - 1].split('%%')[0] : null;
    const payload = {
      ...cond,
      floorId: null,
      areaId: null,
      buildId: null,
      ...(LOCATION[v.length - 1] ? { [`${LOCATION[v.length - 1].type}Id`]: ans } : {}),
    }

    dispatch({
      type: 'device_outdoor_hydrant/updateCond',
      payload,
    })
  }

  loadData = (selectedOptions) => {
    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    dispatch({
      type: 'device_outdoor_hydrant/queryLocation',
      payload: {
        target: {
          id: targetOption.value.split('%%')[0],
          ind: targetOption.value.split('%%')[1],
        },
        option: selectedOptions.map(v => (v.value.split('%%')[1]))
      }
    })
  };

  showUpload = (v) => {
    const { dispatch } = this.props;
    dispatch({ type: 'devices/queryTemple', payload: { type: 'device_outdoor_hydrant' } })
  }

  private handleChange = (type: string, value: number | string) => {
    const { cond = {}, dispatch } = this.props;
    cond[type] = value;

    dispatch({
      type: 'device_outdoor_hydrant/updateCond',
      payload: cond,
    })
  }

  render() {
    const { form, dict = {} } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };
    return (
      <Form onSubmit={this.search}>
        <SearchRow style={{ paddingRight: '40px' }}>
          <SearchCol key={0} span={5} >
            <Form.Item
              {...formItemLayout}
              label='安装位置'
            >
              {getFieldDecorator('buildList')(
                <Cascader
                  options={this.props.location}
                  loadData={this.loadData}
                  changeOnSelect
                  onChange={this.handleSelect}
                  placeholder="请选择"
                />
              )}
            </Form.Item>
          </SearchCol>
          <SearchCol key={1} span={4}>
            <FormItem
              label="联网状态"
              {...formItemLayout}
            >
              {getFieldDecorator('runStatus')(
                DropDownSelectObj({
                  dict, type: 'device.run.status',
                  onChange: (v: any) => this.handleChange('runStatus', +v)
                })
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={4} span={15} >
            <SearchRow type="flex" justify="end">
              <SearchButton htmlType="submit" icon='search'>搜索</SearchButton>
              <SearchButton icon='redo' onClick={(e) => {
                this.props.form.resetFields();
                this.search(e)
              }} style={{ 'marginLeft': '15px' }}>重置</SearchButton>
              <SearchButton icon="select" onClick={this.showUpload} style={{ marginLeft: '15px' }}>导入</SearchButton>
              <Link to='/data/device_outdoor_hydrant/new' style={{ marginLeft: '15px' }}>
                <SearchButton icon='plus' type="primary">新增</SearchButton>
              </Link>
            </SearchRow>
          </SearchCol>
        </SearchRow>
      </Form>
    );
  }
}

const SearchS = Form.create<Props>()(Search);
export default SearchS;
